# 计算欧氏距离(相似度度量)
import json
import numpy as np


def euclidean_score(dataset,user1,user2):
    if user1 not in dataset:
        raise TypeError('User'+user1+'不在数据集中')
    if user2 not in dataset:
        raise TypeError("User"+user2+'不在数据集中')

    # 用户user1和user2都评过分的电影,则分数为0
    rated_by_both = {}
    for item in dataset[user1]:
        if item in dataset[user2]:
            rated_by_both[item] = 1
    if len(rated_by_both) == 0:
        return 0
    squared_differences = []
    for item in dataset[user1]:
        if item in dataset[user2]:
            squared_differences.append(np.square(dataset[user1][item]-dataset[user2][item]))
    return 1 / (1+np.sqrt(np.sum(squared_differences)))


if __name__ == '__main__':
    data_file = 'F:\python学习资料\Python-Machine-Learning-Cookbook-master\Chapter05\movie_ratings.json'
    with open(data_file,'r') as f:
        data = json.loads(f.read())

    user1 = 'John Carson'
    user2 = 'Michelle Peterson'
    print('欧氏距离:')
    print(euclidean_score(data,user1,user2))